package com.supreme.cacheserver.config;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.Serializable;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Data
@Configuration
@ConfigurationProperties(value = "spring.redis")
@ConditionalOnProperty(prefix = "spring.redis.multi-db", name = "enabled", havingValue = "true")
public class RedisMultiConfig {

    @Data
    @ConfigurationPropertiesScan(value = "spring.redis.lettuce")
    static class Lettuce {

        @Data
        @ConfigurationPropertiesScan(value = "spring.redis.lettuce.pool")
        static class Pool {

            private Integer maxActive;

            private Long maxWait;

            private Integer maxIdle;

            private Integer minIdle;
        }

        private Pool pool;
    }

    private String host;

    private Integer port;

    private String password;

    private Long timeout;

    private Lettuce lettuce;

    private RedisConnectionFactory connectionFactory(int database, String host, int port, String password) {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(host);
        configuration.setPort(port);
        if (StringUtils.isNotBlank(password)) {
            configuration.setPassword(password);
        }
        configuration.setDatabase(database);

        GenericObjectPoolConfig<Object> genericObjectPoolConfig = new GenericObjectPoolConfig<>();
        genericObjectPoolConfig.setMaxIdle(lettuce.getPool().getMaxIdle());
        genericObjectPoolConfig.setMinIdle(lettuce.getPool().getMinIdle());
        genericObjectPoolConfig.setMaxTotal(lettuce.getPool().getMaxActive());
        genericObjectPoolConfig.setMaxWait(Duration.ofMillis(lettuce.getPool().getMaxWait()));

        LettuceClientConfiguration clientConfig = LettucePoolingClientConfiguration.builder()
                .commandTimeout(Duration.ofMillis(timeout))
                .poolConfig(genericObjectPoolConfig)
                .build();

        LettuceConnectionFactory lettuce = new LettuceConnectionFactory(configuration, clientConfig);
        lettuce.afterPropertiesSet();
        return lettuce;
    }

    private RedisTemplate<String, Serializable> createRedisTemplate(int database) {
        RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<>();
        RedisConnectionFactory connectionFactory = this.connectionFactory(database, host, port, password);
        redisTemplate.setConnectionFactory(connectionFactory);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();

        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(genericJackson2JsonRedisSerializer);

        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        redisTemplate.afterPropertiesSet();

        return redisTemplate;
    }

    @Bean(name = "redisTemplateList")
    public List<RedisTemplate<String, Serializable>> redisTemplateList() {
        List<RedisTemplate<String, Serializable>> redisTemplateList = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            RedisTemplate<String, Serializable> redisTemplate = this.createRedisTemplate(i);
            redisTemplateList.add(redisTemplate);
        }

        return redisTemplateList;
    }
}
